bash
This demonstrates using the IFS
variable to split a comma-separated string and iterate over its elements in a for
loop.
IFS=',' string="apple,banana,cherry" for fruit in $string; do echo "Fruit: $fruit" done
bash internaldata manipulationsstring manipulation and expansionsIFS
(Internal Field Separator)
bash
This demonstrates the usage of the printf
command in Bash for formatted output, including strings, integers, floats, and writing to files.
printf "Hello %s, I'm %s" Sven Olga #=> "Hello Sven, I'm Olga printf "1 + 1 = %d" 2 #=> "1 + 1 = 2" printf "This is how you print a float: %f" 2 #=> "This is how you print a float: 2.000000" printf '%s\n' '#!/bin/bash' 'echo hello' >file # format string is applied to each group of arguments printf '%i+%i=%i\n' 1 2 3 4 5 9
bash internaldata manipulationsstring manipulation and expansionsformatted output
bash
This demonstrates special string slicing and substitution using parameter expansion.
name="John" echo "${name}" echo "${name/J/j}" #=> "john" (substitution) echo "${name:0:2}" #=> "Jo" (slicing) echo "${name::2}" #=> "Jo" (slicing) echo "${name::-1}" #=> "Joh" (slicing) echo "${name:(-1)}" #=> "n" (slicing from right) echo "${name:(-2):1}" #=> "h" (slicing from right) echo "${food:-Cake}" #=> $food or "Cake"
bash internaldata manipulationsstring manipulation and expansionsparameter expansionstring slicing
bash
This demonstrates extracting the base filename and directory path from a file path using parameter expansion.
src="/path/to/foo.cpp" base=${src##*/} #=> "foo.cpp" (basepath) dir=${src%$base} #=> "/path/to/" (dirpath)
bash internaldata manipulationsstring manipulation and expansionsparameter expansionpath manipulation